package com.bawei.demo_mvvm

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/**
 * @author yaotianxue
 * @description 封装所有扩展函数
 * @date 2025/5/12
 */


fun <T> Flow<T>.observeWithLifecycle(
    lifecycleOwner: LifecycleOwner,
    minState:Lifecycle.State = Lifecycle.State.RESUMED,
    action:suspend (T) -> Unit
):Job = lifecycleOwner.lifecycleScope.launch {
    lifecycleOwner.repeatOnLifecycle(minState){
        collectLatest {
            action.invoke(it)
        }
    }
}